<template>
    <div v-loading="loading" style="width: 100%;">
        <SavePage :title="id ? '编辑养护工程' : '新增养护工程'">
            <template slot="buttons">
                <BaseButton :loading="submitLoading"  :disabled="submitDisabled" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基础信息" />
                <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="88px" style="max-width: 900px;">
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <el-form-item label="项目名称" prop="name"> 
                                <el-input
                                v-model="form.name"
                                placeholder="请输入"
                                clearable
                                maxlength="100"
                                type="textarea"
                                :autosize="{ minRows: 1, maxRows: 4}"
                                show-word-limit
                            ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="类型" prop="type">
                                <el-select v-model="form.type" style="width: 100%;" clearable>
                                    <el-option v-for="item in engineeringTypeOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="所属公路" prop="highwayCode">
                                <RoadSelect :value.sync="form.highwayCode" :name.sync="form.highwayName"  :clearable="true"></RoadSelect>
                            </el-form-item>
                        </el-col>
                        
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="建设地点" prop="constructAddress">
                                <el-input v-model="form.constructAddress" placeholder="请输入" clearable maxlength="100" show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="工程预算" prop="budgetAmount">
                                <el-input v-model="form.budgetAmount" clearable placeholder="输入金额">
                                    <template slot="append"><span>万元</span></template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="施工单位" prop="contractorId">
                                <el-select v-model="form.contractorId" style="width: 100%;" @change="handleChangeOrg1">
                                    <el-option v-for="item in orgOptions1" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                </el-select> 
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="监理单位" prop="supervisorId">
                                <el-select v-model="form.supervisorId" style="width: 100%;" @change="handleChangeOrg2">
                                    <el-option v-for="item in orgOptions2" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                </el-select> 
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12">
                            <el-form-item label="计划工期" prop="date">
                                <el-date-picker
                                    v-model="form.date"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="工程概况" prop="remark">
                                <el-input
                                    v-model="form.remark"
                                    type="textarea"
                                    placeholder="请输入"
                                    maxlength="1000"
                                    :autosize="{ minRows: 2, maxRows: 4}"
                                    show-word-limit
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <TitleTips title="附件资料" />
                <FileUpload ref="fileUpload" :list="form.filesUrl" @load="handleLoad" />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { ProjectLedgerModel, ContractModel } from '@/models'
import { EngineeringTypeOptions } from '../../../constants'
import { isNumber6 } from '@/utils/validate'

export default {
    name: 'ProjectLedgerAdd',
    data() {
        return {
            model: new ProjectLedgerModel(),
            contractModel: new ContractModel(),
            engineeringTypeOptions: EngineeringTypeOptions,
            loading: false,
            submitDisabled: false,
            submitLoading: false,
            id: '',
            form: {
                name: '',
                type: '',
                highwayCode: '',
                highwayName: '',
                constructAddress: '',
                budgetAmount: '',
                contractorId: '',
                contractorName: '',
                supervisorId: '',
                supervisorName: '',
                date: '',
                remark: '',
                filesUrl: []
            },
            rules: {
                name: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validNameUnique, trigger: ['blur'] }
                ],
                type: [{ required: true, message: '请选择', trigger: 'change' }],
                highwayCode: [{ required: true, message: '请选择', trigger: 'change' }],
                constructAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
                budgetAmount: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validNum, trigger: 'blur' }
                ],
                contractorId: [{ required: true, message: '请选择', trigger: 'change' }],
                supervisorId: [{ required: true, message: '请选择', trigger: 'change' }],
                date: [{ required: true, message: '请选择', trigger: 'change' }],
                remark: [{ required: true, message: '请输入', trigger: 'blur' }]
            },
            orgOptions1: [],
            orgOptions2: [],
        }
    },
    created() {
        this.getQuery()
        this.id && this.getDetail()
        this.getContractorList1()
        this.getContractorList2()
    },
    methods: {
        getQuery() {
            const type = this.$route.query.type
            this.id = this.$route.query.id || ''
            if (type === 'edit') {
                this.loading = true
            }
        },
        handleChangeOrg1(value) {
            const target = this.orgOptions1.find(item => item.value === value) || {}
            this.form.contractorName = target.label
        },
        handleChangeOrg2(value) {
            const target = this.orgOptions2.find(item => item.value === value) || {}
            this.form.supervisorName = target.label
        },
        validNum(rule, value, callback) {
            if (value && !isNumber6(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validNameUnique(rule, value, callback) {
            this.model.validNameUnique({ name: value, id: this.form.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('养护工程名称已存在'))
                } else {
                    callback()
                }
            }).finally(() => {
                this.submitLoading = false
            })
        },
        handleLoad(value) {
            this.submitDisabled = value
        },
        getContractorList1() {
            this.contractModel.contractorList({type: 2}).then(res => {
                this.orgOptions1 = (res || []).map(item => {
                    return {
                        label: item.orgName,
                        value: Number(item.orgId)
                    }
                })
            })
        },
        getContractorList2() {
            this.contractModel.contractorList({type: 3}).then(res => {
                this.orgOptions2 = (res || []).map(item => {
                    return {
                        label: item.orgName,
                        value: Number(item.orgId)
                    }
                })
            })
        },
        getDetail() {
            this.model.detail({ id: this.id }).then(res => {
                this.form = res
                this.form.filesUrl = this.form.filesUrl ? JSON.parse(this.form.filesUrl) : []
                this.form.date = [this.form.startDate, this.form.endDate]
            }).finally(() => {
                this.loading = false
            })
        },
        submit() {
            this.submitLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const filesUrl = JSON.stringify(this.$refs['fileUpload'].getFileList())
                    console.log(filesUrl)
                    const [startDate = null, endDate = null] = this.form.date
                    const data = {
                        ...this.form,
                        id: this.id,
                        startDate,
                        endDate,
                        filesUrl
                    }
                    this.model.saveOrUpdate(data).then(() => {
                        this.$message({
                            type: 'success',
                            message: '操作成功！',
                            duration: 500,
                            onClose: () => {
                                this.$router.go(-1)
                            }
                        })
                    }).finally(() => {
                        this.submitLoading = false
                    })
                } else {
                    this.submitLoading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>

</style>
